package com.hst.web.base.web;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hst.core.ServiceContext;
import com.hst.core.dao.IORDao;
import com.hst.core.dao.ISQLDao;
import com.hst.core.dao.ORQuery;
import com.hst.core.dao.ORQuery.Op;
import com.hst.core.json.JsonUtil;
import com.hst.web.auth.po.User;
import com.hst.web.base.entity.TCompanyContractor;
import com.hst.web.base.entity.TCompanyEmployee;
import com.hst.web.base.entity.TContract;
import com.hst.web.base.entity.TContractorInfo;
import com.hst.web.base.service.*;
import com.hst.web.base.ui.*;
import com.hst.web.common.utils.ScpUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Base64.Encoder;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipFile;

@Controller
@RequestMapping("/contractor")
public class ContractorController {
    static Logger logger = LoggerFactory.getLogger(ContractorController.class);

    @Autowired
    ISQLDao sql;

    @Autowired
    IORDao dao;

    @Autowired
    EmployeeService empService;

    @Autowired
    VehicleService vService;

    @Autowired
    ContractorService service;

    @Autowired
    private TContractService tContractService;

    @Value("${file.host}")
    private String host;

    @Value("${file.username}")
    private String username;

    @Value("${file.password}")
    private String password;

    @SuppressWarnings({"unchecked"})
    private Map<String, Object> parseQuerys(String data) throws JsonParseException, JsonMappingException, IOException {
        Map<String, Object> querys = JsonUtil.read(data, Map.class);
        return querys;
    }

    @Value("${import-contractor-emp-template}")
    private String importEmpTemplate;

    @Value("${import-contractor-veh-template}")
    private String importVehTemplate;

    @Value("${file.storage.path}")
    private String fileStoragePath; // 替换为实际文件存储路径

    @RequestMapping("/contractor-all")
    public void all(Model m) {
        User u = (User) ServiceContext.getInstance().getUser();
        String companyCode = u.getCompanyCode();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("companyCode", companyCode);
        m.addAttribute("contractor-all", sql.query("dicts.contractor-all", params));
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("/contractor-info")
    public void info(@RequestBody(required = false) String data, Model m)
            throws JsonParseException, JsonMappingException, IOException {
        User u = (User) ServiceContext.getInstance().getUser();
        String companyCode = u.getCompanyCode();

        Map<String, Object> params;
        if (!StringUtils.isEmpty(data))
            params = JsonUtil.read(data, Map.class);
        else
            params = new HashMap<String, Object>();
        if (!StringUtils.isEmpty(companyCode) && !params.containsKey("user_companycode"))
            params.put("user_companycode", companyCode);

        params.put("userid", u.getId());
        if ("1".equals(u.getUserType()))// 承包商管理员
            m.addAttribute("contractor-info", sql.query("contractor.contractor-info1", params));
        if ("2".equals(u.getUserType()) || "9".equals(u.getUserType()))// 企业,公安
            m.addAttribute("contractor-info", sql.query("contractor.contractor-info2", params));
    }

    /**
     * 导入承包商
     *
     * @param company
     * @param file
     * @param m
     * @throws IOException
     */
    @RequestMapping("/import-employee")
    public void importEmployee(@RequestParam(value = "company", required = false) String company,
                               @RequestParam(value = "upload") MultipartFile file, Model m) throws IOException {
        try {
            empService.importContractorEmployee(company, file, m);
            logger.info("importEmployee 导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("importEmployee报错了， 错误:", e.getMessage());
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("msg", e.getMessage());
            map.put("code", "0");
            m.addAttribute("error", map);
        }
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("/contractor-employee")
    public void dictContractorEmployeeInfo(@RequestBody(required = false) String data, Model m)
            throws JsonParseException, JsonMappingException, IOException {
        Map<String, Object> params;
        if (data != null)
            params = JsonUtil.read(data, Map.class);
        else
            params = new HashMap<String, Object>();
        UserRoleService.addContractorEmpParam(params);
        m.addAttribute("contractor-employee", sql.query("contractor.contractor-employee", params));
    }

    @RequestMapping("/contractorDetail")
    public void contractorDetail(@RequestBody String data, Model m)
            throws JsonParseException, JsonMappingException, IOException {
        Map<String, Object> params = parseQuerys(data);
        String contractorCode = (String) params.get("contractorCode");
        TContractorInfo contractor = dao.get(TContractorInfo.class, contractorCode);
        m.addAttribute("contractor", JsonUtil.toString(contractor));
    }

    @RequestMapping("/download-employee-template")
    public void downloadTempate(HttpServletResponse res) throws IOException {
        File file = new File(importEmpTemplate);
        try (InputStream bis = new BufferedInputStream(new FileInputStream(file))) {
            try (BufferedOutputStream bos = new BufferedOutputStream(res.getOutputStream())) {
                IOUtils.copy(bis, bos);
            }
        }
    }

    @RequestMapping("/download-vehicle-template")
    public void downloadVehicleTempate(HttpServletResponse res) throws IOException {
        File file = new File(importVehTemplate);
        try (InputStream bis = new BufferedInputStream(new FileInputStream(file))) {
            try (BufferedOutputStream bos = new BufferedOutputStream(res.getOutputStream())) {
                IOUtils.copy(bis, bos);
            }
        }
    }

    @RequestMapping("/contractorEmployeeDetail")
    public void contractorEmployeeDetail(@RequestBody String data, Model m)
            throws JsonParseException, JsonMappingException, IOException {
        ContractorEmployee contractorEmployee = null;
        Map<String, Object> params = parseQuerys(data);
        UserRoleService.addContractorEmpParam(params);
        List<ContractorEmployee> contractorEmployeeList = (List<ContractorEmployee>) sql.query("employee.list-contractor-employee", params);
        if (contractorEmployeeList.size() > 0) {
            contractorEmployee = contractorEmployeeList.get(0);
        }
        m.addAttribute("employee", JsonUtil.toString(contractorEmployee));
    }

    @RequestMapping("/personReceiveBack")
    public void personReceiveBack(@RequestBody String data, Model m) throws JsonParseException, JsonMappingException,
            IOException, IllegalAccessException, InvocationTargetException {
        PersoneltransferInfo person = JsonUtil.read(data, PersoneltransferInfo.class);
        empService.transBack(person, m);
    }

    @RequestMapping("/personReceivePass")
    public void personReceivePass(@RequestBody String data, Model m) throws JsonParseException, JsonMappingException,
            IOException, IllegalAccessException, InvocationTargetException {
        PersoneltransferInfo person = JsonUtil.read(data, PersoneltransferInfo.class);
        empService.transPassCont(person, m);
    }

    /**
     * 通过社会信用代码找到承包商
     *
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonParseException
     */
    @RequestMapping("/creditNumContractor")
    public void creditNumContractor(@RequestBody String data, Model m)
            throws JsonParseException, JsonMappingException, IOException {
        Map<String, Object> params = parseQuerys(data);
        String creditCode = (String) params.get("creditCode");
        List<ORQuery> querys = new ArrayList<ORQuery>();
        querys.add(new ORQuery(Op.eq, "creditCode", creditCode));
        List<TContractorInfo> contractors = dao.list(TContractorInfo.class, querys);
        if (contractors.size() > 0) {
            User u = (User) ServiceContext.getInstance().getUser();
            TContractorInfo contractor = contractors.get(0);
            querys = new ArrayList<ORQuery>();
            querys.add(new ORQuery(Op.eq, "companyCode", u.getCompanyCode()));
            querys.add(new ORQuery(Op.eq, "contractorCode", contractor.getContractorCode()));
            List<TCompanyContractor> rels = dao.list(TCompanyContractor.class, querys);
            if (rels.size() > 0) {
                m.addAttribute("msg", "error");
            } else {
                m.addAttribute("contractor", JsonUtil.toString(contractors.get(0)));
            }
        }
    }

    @RequestMapping("/saveContractor")
    public void saveContractor(@RequestBody String data, Model m) throws Exception {
        Map<String, Object> params = parseQuerys(data);
        String contracotrStr = (String) params.get("contractor");
        String op = (String) params.get("op");
        service.saveContractor(op, contracotrStr, m);
    }

    @RequestMapping("/delContract")
    public void delContract(@RequestBody String data, Model m)
            throws JsonParseException, JsonMappingException, IOException {
        List<ContractorInfo> contractors = JsonUtil.readList(data, ContractorInfo.class);
        service.delContract(contractors);
    }

    @RequestMapping("/contractorUpgrade")
    public void contractorUpgrade(@RequestBody String data, Model m)
            throws JsonParseException, JsonMappingException, IOException {
        Map<String, Object> params = parseQuerys(data);
        String employee = (String) params.get("employee");
        String contractor = (String) params.get("contractor");
        String password = (String) params.get("passwd");
        String role = (String) params.get("role");
        Encoder encoder = Base64.getEncoder();


//		password = new String(encoder.encodeToString(password.getBytes()));
        String account = (String) params.get("account");

        System.out.println(account);
        service.contractorUpgrade(employee, role, password, account, m);
    }

    @RequestMapping("/delgrade")
    public void delgrade(@RequestBody String data, Model m) throws JsonParseException, JsonMappingException, IOException {
        ContractorUpgrade upgrade = JsonUtil.read(data, ContractorUpgrade.class);
        service.delgrade(upgrade, m);
    }

    /**
     * 查询历史合同
     *
     * @param papersNumber
     * @return
     * @throws Exception
     */
    @PostMapping("/queryHisContract")
    public HisContractResult queryHisContract(String papersNumber) throws Exception {
        HisContractResult result = new HisContractResult();
        List<TContractDTO> listData = new ArrayList<>();
        try {
            User u = (User) ServiceContext.getInstance().getUser();
            logger.info("当前用户：" + u.getCompanyCode());
            logger.info("当前用户：" + u.getContractorCode());
            if (StringUtils.isEmpty(papersNumber)) {
//				throw new Exception("证件号为空");
                result.setCode("0001");
                result.setMessage("证件号为空");
                logger.info("queryHisContract接口 返回:证件号为空");
                return result;
            }

            listData = tContractService.hisContract_One(papersNumber);
            if (CollUtil.isEmpty(listData)) {
//				throw new Exception("证件号为空");
                result.setCode("0000");
                result.setMessage("暂未查到数据");
                logger.info("UploadContract接口 返回:暂未查到数据");
                return result;
            }
            logger.info(" 336 查询结果：" + listData);

            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(listData);
//			logger.info("查询结果："+json);

            result.setCode("0000");
            result.setData(listData);
            result.setMessage("查询成功");
            logger.info("queryHisContract接口 查询成功");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            result.setCode("0001");
            result.setMessage("查询失败");
            logger.error("queryHisContract 接口报错， 错误信息" + e.getMessage());
        }

        return result;
    }

    /**
     * 查询有效的合同
     *
     * @param papersNumber
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping("/getContract")
    public HisContractResult getContract(String papersNumber, HttpServletResponse response) throws Exception {
        HisContractResult result = new HisContractResult();
        try {

            if (StringUtils.isEmpty(papersNumber)) {
//				throw new Exception("证件号为空");
                result.setCode("0001");
                result.setMessage("证件号为空");
                logger.info("getContract 证件号为空");
                return result;
            }
            List<TContract> contracts = tContractService.getContract(papersNumber);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(contracts);
//			logger.info("查询结果："+json);
            if (CollUtil.isEmpty(contracts)) {
//				throw new Exception("暂未查到数据");
                result.setCode("0000");
                result.setMessage("暂未查到数据");
                logger.info("getContract 暂未查到数据");
                return result;
            }

            result.setCode("0000");
            result.setData(contracts.get(0));
            result.setMessage("查询成功");
            logger.info("getContract 查询成功");
            return result;

        } catch (Exception e) {
            e.printStackTrace();
            result.setCode("0001");
            result.setMessage("上传失败！原因：" + e.getMessage());
            logger.error("getContract 接口报错, 报错内容为：" + e);
        }

        //ResponseEntity<Resource> responseEntity = serveFile(contract.getFileName(), type);
        return result;
    }

    /**
     * 保存合同
     *
     * @param contractDTO
     * @return
     * @throws IOException
     * @throws ParseException
     */
    @PostMapping("/addContract")
    public HisContractResult addContract(ContractDTO contractDTO) throws IOException, ParseException {
        //文件名带后缀
        try {
            doSave(contractDTO);
            return HisContractResult.success("上传文件成功！");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上传文件异常", e);
        }
        return HisContractResult.fail("上传文件失败!");
    }

    /**
     * 单文件上传接口
     *
     * @param newFile
     * @return filePath
     * @throws IOException
     * @throws ParseException
     */
    @PostMapping("/UploadContract")
    public HisContractResult UploadContract(MultipartFile newFile) throws IOException, ParseException {
        HisContractResult result = new HisContractResult();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String fold = "../filestorecontract/" + DateUtil.format(DateUtil.date(), "yyyyMMdd");//存储路径
        String fold2 = "/contract/" + DateUtil.format(DateUtil.date(), "yyyyMMdd");
        try {
            File file = new File(fold + File.separator);
            File file2 = new File(fold2 + File.separator);
            if (!file.exists()) {
                file.mkdirs();
            }
            //文件名带后缀
            String orgName = newFile.getOriginalFilename();

            //生成新文件名
            String fileName = null;
            if (orgName.contains(".")) {
                fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
            }

            //将用户上传的文件复制到指定目录
            String savePath = file.getPath() + File.separator + fileName;
            File saveFile = new File(savePath);
            FileCopyUtils.copy(newFile.getBytes(), saveFile);

            String filePath = file2.getPath() + File.separator + fileName;
//			System.out.println("文件路径："+filePath);
            logger.info("文件路径：" + filePath);

            backupToServer(Collections.singletonList(saveFile), fileStoragePath);

            result.setCode("0000");
            result.setData(filePath);
            result.setMessage("上传成功");
            logger.info("UploadContract接口 操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode("0001");
            result.setMessage("上传失败！原因：" + e.getMessage());
            logger.error("UploadContract接口报错, 报错内容为：" + e);
        }

        return result;
    }


    /**
     * 批量导入
     *
     * @param contractDTO
     * @param personFile
     * @param contractFile
     * @param mode
     * @throws IOException
     * @throws ParseException
     */
    @PostMapping("/addContract/batch")
    public void addContractBatch(ContractDTO contractDTO, MultipartFile personFile, MultipartFile contractFile, Model mode) throws IOException, ParseException {
        String orgName = contractFile.getOriginalFilename();
        try {
            if (personFile.getSize() > 10 * 1024 * 1024 || contractFile.getSize() > 10 * 1024 * 1024) {
                throw new Exception("文件大小超过10M!");
            }
            //文件名带后缀
            List<ContractDTO> contractDTOList;
            if (personFile.getOriginalFilename().contains(".xls") || personFile.getOriginalFilename().contains(".xlsx")) {
                contractDTOList = getExcelPersons(contractDTO.getCompanyCode(), contractDTO.getContractorCode(), personFile);
            } else {
                throw new Exception("导入文件格式错误！");
            }
            if (CollUtil.isEmpty(contractDTOList)) {
                throw new Exception("导入信息为空！");
            }
            Map<String, ContractDTO> contractDTOMap = contractDTOList.stream().collect(Collectors.toMap(ContractDTO::getPapersNumber, Function.identity(), (o1, o2) -> o1));
            contractDTOList.removeAll(contractDTOMap.values());
            if (!CollUtil.isEmpty(contractDTOList)) {
                throw new Exception("导入人员身份证信息有重复，重复身份证号 {}" + contractDTOList.get(0).getPapersNumber());
            }
            // zip包进行解压
            Map<String, ContractDTO> failList = new HashMap<>();
            Map<String, String> failMsgList = new HashMap<>();
            int i = 0;
            for (ContractDTO dto : contractDTOMap.values()) {
                i++;
                List<ORQuery> querys = new ArrayList<ORQuery>();
                querys.add(new ORQuery(Op.eq, "papersNumber", dto.getPapersNumber()));
                List<TCompanyEmployee> list = dao.list(TCompanyEmployee.class, querys);
                if (list.size() == 0) {
                    dto.setEmployeeCode(list.get(0).getEmployeeCode());
                    failList.put(i + "", dto);
                    failMsgList.put(i + "", "身份证号对应人员信息不存在");
                    continue;
                }
                // 日期校验
                if (!StrUtil.isEmpty(dto.getStartTime()) && !StrUtil.isEmpty(dto.getEndTime())) {
                    if (DateUtil.parseLocalDateTime(dto.getStartTime()).isAfter(DateUtil.parseLocalDateTime(dto.getEndTime()))) {
                        failList.put(i + "", dto);
                        failMsgList.put(i + "", "合同开始日期大于结束日期");
                        continue;
                    }
                }
                doSave(dto, contractFile.getOriginalFilename(), contractFile.getInputStream());
            }
            if (failList.size() > 0) {
                mode.addAttribute("fail", JsonUtil.toString(failList));
                mode.addAttribute("failMsg", failMsgList);
            }
            mode.addAttribute("sucess", true);
        } catch (Exception e) {
            logger.error("上传文件异常", e);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("msg", e.toString());
            map.put("code", "0");
            mode.addAttribute("error", map);
        }
    }

    /**
     * 删除已离职的承包商合同
     *
     * @param contractDTO
     */
    @PostMapping("/delContract")
    public void delCntract(ContractDTO contractDTO, Model mode) throws JsonParseException, JsonMappingException, IOException {
        delHis(contractDTO);
    }


    private List<File> getAllContracts(File tempFile, MultipartFile contractFile) {
        List<File> files = new ArrayList<>();
        String orgName = contractFile.getOriginalFilename();
        File zipDir = null;
        ZipFile zipFile = null;
        try {
            if (orgName != null && orgName.endsWith(".zip")) {
                FileCopyUtils.copy(contractFile.getBytes(), tempFile);
                zipFile = new ZipFile(tempFile);
                // 压缩包文件校验
                List<String> fileNames = ZipUtil.listFileNames(zipFile, "'");
                for (String fileName : fileNames) {
                    if (fileName.contains("..") || fileName.endsWith(".exe") || fileName.endsWith(".sh")) {
                        logger.error("上传文件格式错误！！");
                        return files;
                    }
                }
                zipDir = ZipUtil.unzip(tempFile);

                if (zipDir.listFiles() != null) {
                    files.addAll(Arrays.asList(zipDir.listFiles()));
                }
            } else {
                FileCopyUtils.copy(contractFile.getBytes(), tempFile);
                files.add(tempFile);
            }
        } catch (IOException e) {
            logger.error("获取合同文件失败！");
        } finally {
            if (zipFile != null) {
                try {
                    zipFile.close();
                } catch (IOException e) {
                    logger.error("关闭zip失败", e);
                }
            }
            if (zipDir.exists()) {
                zipDir.delete();
            }
        }
        return files;
    }

    private List<ContractDTO> getExcelPersons(String companyCode, String contractorCode, MultipartFile personFile) {
        List<ContractDTO> dtoList = new ArrayList<>();
        try {
            ExcelReader excelReader = ExcelUtil.getReader(personFile.getInputStream());
            List<List<Object>> lists = excelReader.read(1);
            for (List<Object> list : lists) {
                ContractDTO dto = new ContractDTO();
                if (null != list) {
                    dto.setContractorCode(contractorCode);
                    dto.setCompanyCode(companyCode);
                    if (null != list.get(0)) {
                        dto.setFullname(String.valueOf(list.get(0)));
                    }
                    if (null != list.get(1)) {
                        dto.setPapersNumber(String.valueOf(list.get(1)));
                    }
                    if (!Objects.isNull(list.get(3))) {
                        dto.setStartTime(String.valueOf(list.get(3)));
                    }
                    if (!Objects.isNull(list.get(4))) {
                        dto.setEndTime(String.valueOf(list.get(4)));
                    }
                    dtoList.add(dto);
                }

            }

        } catch (IOException e) {
            logger.error("人员导入excel解析失败", e);
        }
        return dtoList;
    }

    /**
     * 保存方法
     *
     * @param contractDTO
     * @param fileName
     * @param inputStream
     * @throws Exception
     */
    @Transactional
    public void doSave(ContractDTO contractDTO, String fileName, InputStream inputStream) throws Exception {
        User u = (User) ServiceContext.getInstance().getUser();
        Date currentTimeMillis = new Date();
        logger.info("创建时间:" + new Timestamp(currentTimeMillis.getTime()));
        if (contractDTO == null) {
            return;
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String fold = "../filestorecontract/" + DateUtil.format(DateUtil.date(), "yyyyMMdd");//存储路径
        String fold2 = "/contract/" + DateUtil.format(DateUtil.date(), "yyyyMMdd");

        TContract tContract = new TContract();
        tContract.setPapersNumber(contractDTO.getPapersNumber());
        tContract.setContractorCode(contractDTO.getContractorCode());
        tContract.setCompanyCode(contractDTO.getCompanyCode());

        if (!StrUtil.isEmpty(contractDTO.getEmployeeCode())) {
            tContract.setEmployeeCode(contractDTO.getEmployeeCode());
        }

        File file = new File(fold + File.separator);
        File file2 = new File(fold2 + File.separator);
        if (!file.exists()) {
            file.mkdirs();
        }
        //生成新文件名
        String newFileName = null;
        if (fileName.contains(".")) {
            newFileName = fileName.substring(0, fileName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
        }

        //将用户上传的文件复制到指定目录
        String savePath = file.getPath() + File.separator + newFileName;
        File saveFile = new File(savePath);
        FileCopyUtils.copy(inputStream, new FileOutputStream(saveFile));

        //将文件保存数据库
//		tContract.setContractCode(uuid());
        tContract.setFileName(newFileName);
        tContract.setCreateTime(new Timestamp(currentTimeMillis.getTime()));
        tContract.setOpUser(u.getName());
//        tContract.setOpUser("system");
        tContract.setStatus("1");
        tContract.setIsDel("2");
        tContract.setStoragePath(file2.getPath() + File.separator + newFileName);

        if (fileName.endsWith(".jpg") || fileName.endsWith(".png")) {
            tContract.setFileType("3");
        } else if (fileName.endsWith(".pdf")) {
            tContract.setFileType("2");
        } else if (fileName.endsWith(".zip") || fileName.endsWith(".rar")) {
            tContract.setFileType("1");
        }

        if (!StrUtil.isEmpty(contractDTO.getStartTime())) {
            Date startDate = dateFormat.parse(contractDTO.getStartTime());
            tContract.setStartTime(new Timestamp(startDate.getTime()));
        }
        if (!StrUtil.isEmpty(contractDTO.getEndTime())) {
            Date endDate = dateFormat.parse(contractDTO.getEndTime());
            tContract.setEndTime(new Timestamp(endDate.getTime()));
        }

        updateHis(tContract);
        backupToServer(Collections.singletonList(saveFile), fileStoragePath);
        dao.save(tContract);
    }

    @Transactional
    public void doSave(ContractDTO contractDTO) throws Exception {
        User u = (User) ServiceContext.getInstance().getUser();
        Date currentTimeMillis = new Date();
        logger.info("创建时间:" + new Timestamp(currentTimeMillis.getTime()));
        if (contractDTO == null) {
            return;
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        TContract tContract = new TContract();
        tContract.setPapersNumber(contractDTO.getPapersNumber());
        tContract.setContractorCode(contractDTO.getContractorCode());
        tContract.setCompanyCode(contractDTO.getCompanyCode());

        if (!Objects.equals(contractDTO.getEmployeeCode(), "null")) {
            tContract.setEmployeeCode(contractDTO.getEmployeeCode());
        }

        String fileName = contractDTO.getFileName();

        //生成新文件名
        String newFileName = null;
        if (fileName.contains(".")) {
            newFileName = fileName.substring(0, fileName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
        }

        //将文件保存数据库
//		tContract.setContractCode(uuid());
        tContract.setFileName(newFileName);
        tContract.setCreateTime(new Timestamp(currentTimeMillis.getTime()));
//		tContract.setOpUser(u.getName());
        tContract.setOpUser("system");
        tContract.setStatus("1");
        tContract.setIsDel("2");
        tContract.setStoragePath(contractDTO.getFilePath());

        if (fileName.endsWith(".jpg") || fileName.endsWith(".png")) {
            tContract.setFileType("3");
        } else if (fileName.endsWith(".pdf")) {
            tContract.setFileType("2");
        } else if (fileName.endsWith(".zip") || fileName.endsWith(".rar")) {
            tContract.setFileType("1");
        }

        if (!StrUtil.isEmpty(contractDTO.getStartTime())) {
            Date startDate = dateFormat.parse(contractDTO.getStartTime());
            tContract.setStartTime(new Timestamp(startDate.getTime()));
        }

        if (!StrUtil.isEmpty(contractDTO.getEndTime())) {
            Date endDate = dateFormat.parse(contractDTO.getEndTime());
            tContract.setEndTime(new Timestamp(endDate.getTime()));
        }


        List<TContract> contracts = tContractService.getContract_One(tContract.getPapersNumber());
        if (!contracts.isEmpty()) {
            Timestamp contract_StartTime = contracts.get(0).getStartTime();
            Timestamp contract_EndTime = contracts.get(0).getEndTime();
            String contract_StoragePath = contracts.get(0).getStoragePath();
            Timestamp tContract_StartTime = tContract.getStartTime();
            Timestamp tContract_EndTime = tContract.getEndTime();
            String tContract_StoragePath = tContract.getStoragePath();
            if (contract_StartTime.equals(tContract_StartTime) && contract_EndTime.equals(tContract_EndTime) && contract_StoragePath.equals(tContract_StoragePath)) {
                updateHis_doSave(tContract);
            } else {
                updateHis(tContract);
                dao.save(tContract);
            }
        } else {
            dao.save(tContract);
        }
    }

    // 文件保存到三方服务器
    private void backupToServer(List<File> list, String storagePath) {
        ScpUtil.initSession(ScpUtil.getInstance(), username, password, host);
        ScpUtil.uploadFiles(list, storagePath);
    }

    // 原有 
    private void updateHis(TContract tContract) throws JsonProcessingException {
        User u = (User) ServiceContext.getInstance().getUser();
        List<TContract> contracts = tContractService.getContract(tContract.getPapersNumber());
        Date currentTime = new Date();
        logger.info("更新时间: " + new Timestamp(currentTime.getTime()));
        contracts.forEach(po -> {

            po.setUpUser("system");
            po.setEmployeeCode(tContract.getEmployeeCode());
            po.setStatus("2");
//			po.setUpUser(u.getName());
            po.setUpdateTime(new Timestamp(currentTime.getTime()));
            dao.update(po);
        });
    }

    private void updateHis_doSave(TContract tContract) throws JsonProcessingException {
        User u = (User) ServiceContext.getInstance().getUser();
        List<TContract> contracts = tContractService.getContract(tContract.getPapersNumber());
        Date currentTime = new Date();
        logger.info("更新时间: " + new Timestamp(currentTime.getTime()));

        if (Objects.equals(contracts.get(0).getEmployeeCode(), "null")) {
            contracts.forEach(po -> {

                po.setUpUser("system");
                po.setEmployeeCode(tContract.getEmployeeCode());
//				po.setUpUser(u.getName());
                po.setUpdateTime(new Timestamp(currentTime.getTime()));
                dao.update(po);
            });
        }

    }

    private void delHis(ContractDTO contractDTO) {
        User u = (User) ServiceContext.getInstance().getUser();
        List<ORQuery> querys = new ArrayList<ORQuery>();
        //清除用户所有合同状态
        querys.clear();
//		querys.add(new ORQuery(Op.eq, "employeeCode", contractDTO.getEmployeeCode()));
        querys.add(new ORQuery(Op.in, "papersNumber", contractDTO.getPapersNumber()));
        List<TContract> List_tContracts = dao.list(TContract.class, querys);
        for (TContract tContract : List_tContracts) {
//			tContract.setUpUser("system");
            tContract.setUpUser(u.getId());
            tContract.setStatus("2");
            tContract.setIsDel("1");
            dao.update(tContract);
        }

    }


    private String guessContentType(String fileName) {
        String extension = FilenameUtils.getExtension(fileName).toLowerCase();
        switch (extension) {
            case "pdf":
                return "application/pdf";
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "rar":
                return "application/x-rar-compressed";
            case "zip":
                return "application/zip";
            default:
                return MediaType.APPLICATION_OCTET_STREAM_VALUE; // 若无法识别类型，返回通用二进制流类型
        }
    }

    private String uuid() {
        long time = System.currentTimeMillis();
        int random = (int) (Math.random() * Integer.MAX_VALUE);
        UUID uuid1 = new UUID(time, random);
        String uuid = uuid1.toString();
        return uuid;
    }
}
